<?php
/**
 * upload文件浏览器
 *
 * @version      0.0.0
 * @author      by huwhois
 * @time        2017/11/27
 */
namespace app\admin\controller;

use think\Request;

class FileManager extends Base
{
    protected $img_path = ROOT_PATH . 'public' . DS . 'uploads'. DS; 
    protected $t_suffix = '_thumb';
    protected $t_width = 384;
    protected $t_height = 224;
    protected $request;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->request = $request;
    }

    public function index()
    {
        $data = $this->explorer();

        $this->assign('dirs', $data['dirs']);
        $this->assign('files', $data['files']);
        $this->assign('counts', $data['counts']);
        $this->assign('activeurl', $data['activeurl']);
        $this->assign('activepath', $data['activepath']);

        return $this->fetch();
    }

    /**
     * 获取当前文件相关信息
     * @return array $data 文件信息数据组
     */
    protected function explorer()
    {
        $param = $this->request->param();
 
        $activepath =  isset($param['activepath'])? $param['activepath'] : '';
        
        $inpath = "";

        $inpath = $this->img_path . $activepath;

        $dirhandle = scandir($inpath);
       
        $dirs = $files = [];

        define('BKM', 1024);
        
        foreach ($dirhandle as $val) {
            if ($val == "." || $val == "..") {
                continue;
            } elseif (is_dir($inpath . DS . $val)) {
                $dirs[] = $val;
            } else {
                $arr = [];
                $file = '';
                $file = $inpath . DS . $val;
                
                $arr['name'] = $val;
                
                $arr['extension'] = pathinfo($file, PATHINFO_EXTENSION);

                $filesize = floatval(filesize($file));
                if ($filesize>BKM) {
                    $filesize =  round($filesize/BKM, 2);

                    if ($filesize>BKM) {
                        $filesize = round($filesize/BKM, 2);
                    
                        $filesize .="M";
                    } else {
                        $filesize .="K";
                    }
                } else {
                    $filesize .="B";
                }
                $arr['size'] = $filesize;

                $filetime = filemtime("$file");
                $arr['time'] = date("Y-m-d H:i:s", $filetime);

                $files[] = $arr;
            }
        }
        $counts = count($dirs)+count($files);

        $activeurl = preg_replace("#[\/][^\/]*$#i", "", $activepath);
       
        $data = [
            'dirs'      => $dirs,
            'files'     => $files,
            'counts'    => $counts,
            'activeurl' => $activeurl,
            'activepath'=> $activepath,
        ];

        return $data;
    }

    public function delDir()
    {
        if ($this->request->isAjax()) {
             $activepath = $this->request->param('activepath');
            $activepath = str_replace('/', DS, $activepath);
            $dir = $this->request->param('dir');

            $dir_name = ROOT_PATH.'public'.DS.$activepath.DS.$dir;
    
            if (count(scandir($dir_name)) > 2) {
                return ['status'=>1,'msg'=>'不可删除非空目录'];
            }

            if (rmdir($dir_name)) {
                return ['status'=>2,'msg'=>'success'];
            } else {
                return ['status'=>0,'msg'=>'failed'];
            }
        }
    }
    
    public function del()
    {
        if ($this->request->isAjax()) {
            $activepath = $this->request->param('activepath');
            $activepath = str_replace('/', DS, $activepath);
            $filename = $this->request->param('filename');

            if (unlink(ROOT_PATH.'public'.DS.$activepath.DS.$filename)) {
                return ['status'=>1,'msg'=>'success'];
            } else {
                return ['status'=>0,'msg'=>'failed'];
            }
        }
    }

    /**
     * 删除文件
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $filename = $param['filename'];
            // var_dump($filename);
            // exit;
            if (is_array($filename)) {
                foreach ($filename as $value) {
                    if(!unlink(ROOT_PATH.'public' . $value)) {
                        return ['code'=>0,'msg'=>'failed'];
                    }
                }
                return ['code'=>1,'msg'=>'success'];
            } else {
                if (unlink(ROOT_PATH.'public' . $filename)) {
                    return ['code'=>1,'msg'=>'success'];
                } else {
                    return ['code'=>0,'msg'=>'failed'];
                }
            }
        }
    }

    public function upload()
    {
        if ($this->request->isGet()) {
            return $this->fetch();
        } else {
            $isthumb = $this->request->has('isthumb', 'post') ? $this->request->post('isthumb') : 0;
            $mode = $this->request->has('formername', 'post') ? $this->request->post('formername') : 0;
            $file = request()->file('image');

            $info = $this->saveUpload($file, $mode);

            if (!$info) {
                $this->error($info->getError());
            }
   
            $filename = $info->getSaveName();
            unset($info);
            if ($isthumb == 1) {
                $width = $this->request->has('width', 'post') ? $this->request->post('width') : $this->t_width;
                $height = $this->request->has('height', 'post') ? $this->request->post('height') : $this->t_height;
                
                $thumbname = $this->makeThumb($filename, $width, $height);

                if (!$thumbname) {
                    $this->error('缩略图生成失败');
                }
            } else {
                $thumbname = '';
            }

            if ($this->request->isAjax()) {
                return ['code'=>2, 'picname' => $filename, 'thumbname'=>$thumbname];
            } else {
                $this->success('上传成功', '/file_manager/index');
            }
        }
    }

    public function uploadimg()
    {
        if ($this->request->isAjax()) {
            $isthumb = $this->request->has('isthumb', 'post') ? $this->request->post('isthumb') : 0;

            $file = request()->file('upload_file');
            if (!$file) {
                $this->error('图片不为空');
            }
            $validate = ['size'=>2097152,'ext'=>'jpg,png,gif,jpeg'];
            $info = $file->validate($validate)->move(ROOT_PATH . 'public' . DS . 'uploads');

            if (!$info) {
                $this->error($file->getError());
            }
   
            $filename = $info->getSaveName();
            unset($info);
            if ($isthumb == 1) {
                // $width = $this->request->has('width', 'post') ? $this->request->post('width') : $this->t_width;
                // $height = $this->request->has('height', 'post') ? $this->request->post('height') : $this->t_height;
                
                $thumbname = $this->makeThumb($filename, 300, 200);

                if (!$thumbname) {
                    $this->error('缩略图生成失败');
                }
            } else {
                $thumbname = '';
            }

            return ['code'=>2, 'picname' => '/uploads/' . str_replace('\\', '/', $filename), 'thumbname'=>'/uploads/' . str_replace('\\', '/', $thumbname)];
        }
    }

    /**
     * 保存上传的图片
     * @param object $file 获取的上传对象
     * @param boolean $mode 是否保存原文件名 0(false), 生成新名称; 1(true), 保留原名
     * @return object 返回文件保存对象
     */
    protected function saveUpload($file, $mode)
    {
        $validate = ['size'=>2097152,'ext'=>'jpg,png,gif,jpeg'];

        if ($mode) {
            $upload = $file->validate($validate)->move(ROOT_PATH . 'public' . DS . 'uploads', '');
        } else {
            $upload = $file->validate($validate)->move(ROOT_PATH . 'public' . DS . 'uploads');
        }

        return $upload;
    }

    /**
     * 生成缩略图
     * @param string $filename 必须参数, 图片路径名(相对or绝对)(/public/uploads/...)
     * @param int $width 缩略图宽值, 默认 280px;
     * @param int $height 缩略图高值, 默认 160px;
     * @param int $type 缩略图裁剪方式, 默认值 6, 固定尺寸缩放; 其他: 1, 等比例缩放;
     * 2, 缩放后填充; 3, 居中裁剪; 4, 左上角裁剪; 5, 右下角裁剪
     * @return string $thumbname 缩略图文件名
     */
    protected function makeThumb($filename, $width = 280, $height = 160, $type = 6)
    {
        $file = $this->img_path . $filename;

        $ext = pathinfo($file, PATHINFO_EXTENSION);
        
        $thumbname = str_replace('.' . $ext, '', $filename) . $this->t_suffix . '.' . $ext;

        $image = \think\Image::open($file);

        $result = $image->thumb($width, $height, $type)->save($this->img_path . $thumbname);
        
        return $result ? $thumbname : false;
    }

    /**
     * 站内选择
     * @return void
     */
    public function selectPicture()
    {
        $data = $this->explorer();

        $this->assign('data', $data);
        return $this->fetch();
    }

    public function uploadPicture()
    {
        return $this->fetch();
    }

    // public function onlinePicture()
    // {
    //     if ($this->request->isAjax()) {
    //         $param = $this->request->param();
    //         $urlimg = $param['filename'];
    //         $download = $param['download'];
    //         $isthumb = $param['isthumb'];
    //         $formername = $param['formername'];

    //         $res = \mylib\GetImageByurl::isImg($urlimg);
    //         if (!$res) {
    //             $this->error('该图片不合法');
    //         } else {
    //             if (!$download) {
    //                 return ['code'=>2,'filename'=>$urlimg];
    //             } else {
    //                 $basepath = \config('url_domain_root') . '/uploads';
    //                 // var_dump($param);
                    
    //                 if ($isthumb!=1  &&  preg_match("#" . $basepath . "#i", $urlimg)) {
    //                     $this->error('图片已在服务其中, 可直接选用');
    //                 }

    //                 // 按文件夹日期夹存放图片
    //                 $today = date('Ymd', time());
    //                 $savePath = $this->img_path . $today;
    //                 if (!is_dir($savePath)) {
    //                     if (mkdir($savePath) == false) {
    //                         $this->error('下载失败, 请稍后重试');
    //                     }
    //                 }
                    
    //                 if ($formername==1) {
    //                     // 获取原文件名
    //                     $fileinfo = pathinfo($urlimg);
    //                     if (!isset($fileinfo['extension']) || !in_array($fileinfo['extension'], ['jpg', 'jpeg', 'png', 'gif'])) {
    //                         $ext = \mylib\GetImageByurl::getEXTENSION($urlimg);
    //                     }
    //                     $filename = $fileinfo['basename'] . '.' . $ext;
    //                 } else {
    //                     $filename = '';
    //                 }
                            
    //                 $filename = \mylib\GetImageByurl::getImageByurl($urlimg, $filename, $savePath);
                    
    //                 if ($filename) {
    //                     // 生成缩略图
    //                     if ($isthumb==1) {
    //                         $width = $this->request->has('width', 'post') ? $this->request->post('width') : $this->t_width;
    //                         $height = $this->request->has('height', 'post') ? $this->request->post('height') : $this->t_height;
                            
    //                         $thumbname = $this->makeThumb($today . DS . $filename, $width, $height);

    //                         if (!$thumbname) {
    //                             $this->error('缩略图生成失败');
    //                         }
    //                     } else {
    //                         $thumbname = '';
    //                     }

    //                     return ['code'=>2, 'filename' => $today . DS . $filename, 'thumbname'=>$thumbname];
    //                 } else {
    //                     $this->error('图片下载失败');
    //                 }
    //             }
    //         }   
    //     } else {
    //         return $this->fetch();
    //     }
    // }

    /**
     * 判断(远程)文件是否为图片
     */
    // public function isImg()
    // {
    //     if ($this->request->isAjax()) {
    //         $filename = $this->request->param('filename');

    //         $res = \mylib\GetImageByurl::isImg($filename);
    //         if (!$res) {
    //             $this->error('该图片不合法');
    //         } else {
    //             return ['code'=>2,'msg'=>'图片地址可用'];
    //         }
    //     }
    // }
}
